package com.yike.user.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yike.common.pagination.PageInfo;
import com.yike.common.pagination.Paging;
import com.yike.common.tool.LoginUtil;
import com.yike.common.tool.StringUtil;
import com.yike.user.entity.Shop;
import com.yike.user.mapper.PlatformDataMapper;
import com.yike.user.param.*;
import com.yike.user.service.*;
import com.yike.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 平台数据管理
 *
 * @author Sakura
 * @since 2024-10-18
 */
@Slf4j
@Service
public class PlatformDataServiceImpl implements PlatformDataService {

    @Autowired
    private PlatformDataMapper platformDataMapper;

    @Override
    public Paging<SearchListVo> getSearchList(SearchPageParam searchPageParam) throws Exception {
        Page<Shop> page = new PageInfo<>(searchPageParam);
        IPage<SearchListVo> iPage = platformDataMapper.getSearchList(page, searchPageParam);
        return new Paging<SearchListVo>(iPage);
    }

    @Override
    public PlatformDataVo getPlatformData(PlatformDataParam platformDataParam) throws Exception {
        // 如果前端没有传日期则根据类型转换日期
        if (StringUtil.isBlank(platformDataParam.getBeginTime()) || StringUtil.isBlank(platformDataParam.getEndTime())) {
            getDateRange(platformDataParam);
        }
        // 实收金额
        BigDecimal actualAmount = platformDataMapper.getActualAmount(platformDataParam.getShopId(), platformDataParam.getAgentId(),
                platformDataParam.getBeginTime(), platformDataParam.getEndTime());

        // 订单量
        Integer orderNumber = platformDataMapper.getOrderNumber(platformDataParam.getShopId(), platformDataParam.getAgentId(),
                platformDataParam.getBeginTime(), platformDataParam.getEndTime());
        BigDecimal orderAverageAmount = BigDecimal.ZERO;  // 初始化均价为0
        if (actualAmount != null && orderNumber != null && orderNumber > 0) {
            orderAverageAmount = actualAmount.divide(new BigDecimal(orderNumber), 2, RoundingMode.HALF_UP);
        }
        // 退款金额
        BigDecimal refundAmount = platformDataMapper.getRefundAmount(platformDataParam.getShopId(), platformDataParam.getAgentId(),
                platformDataParam.getBeginTime(), platformDataParam.getEndTime());
        // 分润金额
        BigDecimal commissionAmount = platformDataMapper.getCommissionAmount(platformDataParam.getShopId(), platformDataParam.getAgentId(),
                platformDataParam.getBeginTime(), platformDataParam.getEndTime());
        // 代理商数量
        Integer agentNumber = platformDataMapper.getAgentNumber(platformDataParam.getShopId(), platformDataParam.getAgentId(),
                platformDataParam.getEndTime());
        // 新增代理商数量
        Integer addAgentNumber = platformDataMapper.getAddAgentNumber(platformDataParam.getShopId(), platformDataParam.getAgentId(),
                platformDataParam.getBeginTime(), platformDataParam.getEndTime());
        // 店铺数量
        Integer shopNumber = platformDataMapper.getShopNumber(platformDataParam.getShopId(), platformDataParam.getAgentId(),
                platformDataParam.getEndTime());
        // 新增店铺数量
        Integer addShopNumber = platformDataMapper.getAddShopNumber(platformDataParam.getShopId(), platformDataParam.getAgentId(),
                platformDataParam.getBeginTime(), platformDataParam.getEndTime());
        // 用户数量
        Integer userNumber = platformDataMapper.getUserNumber(platformDataParam.getEndTime());
        // 新增用户数量
        Integer addUserNumber = platformDataMapper.getAddUserNumber(platformDataParam.getBeginTime(), platformDataParam.getEndTime());

        PlatformDataVo platformDataVo = new PlatformDataVo();
        platformDataVo.setActualAmount(actualAmount);
        platformDataVo.setOrderNumber(orderNumber);
        platformDataVo.setOrderAverageAmount(orderAverageAmount);
        platformDataVo.setRefundAmount(refundAmount);
        platformDataVo.setCommissionAmount(commissionAmount);
        platformDataVo.setAgentNumber(agentNumber);
        platformDataVo.setAddAgentNumber(addAgentNumber);
        platformDataVo.setShopNumber(shopNumber);
        platformDataVo.setAddShopNumber(addShopNumber);
        platformDataVo.setUserNumber(userNumber);
        platformDataVo.setAddUserNumber(addUserNumber);

        return platformDataVo;
    }

    @Override
    public List<SalesActualCountVo> getSalesActualCount(SalesActualCountParam salesActualCountParam) throws Exception {
        // 如果前端没有传日期则根据类型转换日期
        if (StringUtil.isBlank(salesActualCountParam.getBeginTime()) || StringUtil.isBlank(salesActualCountParam.getEndTime())) {
            // 获取日期
            LocalDate date = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 获取当月第一天
            LocalDate firstDayOfMonth = date.withDayOfMonth(1);
            String firstDayStr = firstDayOfMonth.format(formatter);
            // 获取当月最后一天
            LocalDate lastDayOfMonth = date.withDayOfMonth(date.lengthOfMonth());
            String lastDayStr = lastDayOfMonth.format(formatter);

            salesActualCountParam.setBeginTime(firstDayStr);
            salesActualCountParam.setEndTime(lastDayStr);
        }
        return platformDataMapper.getSalesActualCount(salesActualCountParam.getShopId(), salesActualCountParam.getBeginTime(), salesActualCountParam.getEndTime());
    }

    @Override
    public List<PayTypeDataVo> getPayTypeData(PayTypeDataParam payTypeDataParam) throws Exception {
        return platformDataMapper.getPayTypeData(payTypeDataParam.getShopId(), payTypeDataParam.getBeginTime(), payTypeDataParam.getEndTime());
    }

    @Override
    public List<CategorySalesDataVo> getCategorySalesData(CategoryDataParam categoryDataParam) throws Exception {
        return platformDataMapper.getCategorySalesData(categoryDataParam.getShopId(), categoryDataParam.getBeginTime(), categoryDataParam.getEndTime());
    }

    private void getDateRange(PlatformDataParam platformDataParam) {
        if (platformDataParam.getDateType() == null) {
            platformDataParam.setDateType(1);
        }

        LocalDate today = LocalDate.now();
        LocalDate startDate;
        LocalDate endDate;

        switch (platformDataParam.getDateType()) {
            case 2:  // 昨天
                startDate = today.minusDays(1);
                endDate = startDate;
                break;
            case 3:  // 本周
                startDate = today.with(java.time.DayOfWeek.MONDAY);
                endDate = today;
                break;
            case 4:  // 本月
                startDate = today.withDayOfMonth(1);
                endDate = today;
                break;
            default:
                startDate = today;
                endDate = today;
        }

        // 格式化开始和结束时间
        String startDateTime = startDate.atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endDateTime = endDate.atTime(23, 59, 59).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        platformDataParam.setBeginTime(startDateTime);
        platformDataParam.setEndTime(endDateTime);
    }
}
